//
//  EmoticonManeger.swift
//  EmoticonKeyBoard
//
//  Created by Arvin on 15/11/20.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit

class EmoticonManeger: NSObject {
    
    static let shareEmoticonManager = EmoticonManeger()

    var emoticonPackages = [EmoticonPackages]()
    
    func stringToImageTextAttrubed(str: String?, font: UIFont) -> NSMutableAttributedString {
        let textViewAttrubuted = NSMutableAttributedString(string: str!)
        
        // 2 将text文本表情字符串转成图片文本属性
        
        // 2.1 正则截取表情字符串 []是正则中的特殊字符, 需要转译
        // 2.1.1 匹配方案 matchesInString方法 [.*?]->查找出[]中的内容包刮[]的range , 如果有多个查找结构 返回的result中包含多个
        // .*? -> 表示忽略
        let pattern = "\\[.*?\\]"
        // 2.1.2 实例化正则
        let regular = try!NSRegularExpression(pattern: pattern, options: [])
        // 2.1.3 匹配查找的字符串
        let result = regular.matchesInString(str!, options: [], range: NSMakeRange(0, str?.characters.count ?? 0))
        // 这个方法只找到一个就不找了
        // let result = regular.firstMatchInString(str!, options: [], range: NSMakeRange(0, str?.characters.count ?? 0))
        // let n = result?.numberOfRanges
        
        // 2.1.4 获取表情字符的range 倒序遍历
        var count = result.count - 1
        while count >= 0 {
            let range = result[count].rangeAtIndex(0)
            let subStr = (str! as NSString).substringWithRange(range)
            
            // 2.2 遍历emoticonList数组, 查找与表情字符串相等的Emoticon对象
            if let emoticon = getEmoticon(subStr) {
                
                // 2.3 将Emoticon对象的图片转成文本属性
                let attrubed = EmoticonAttachment().getAttubitedString(font, emoticon: emoticon, range: range)
                
                // 2.4 将文本属性替换到text文本属性中
                textViewAttrubuted.replaceCharactersInRange(range, withAttributedString: attrubed)
            }
            
            count--
        }
        return textViewAttrubuted
    }
    
    func getEmoticon(str: String) -> Emoticon?{
        let mg = EmoticonManeger().emoticonPackages
        for p in mg {
            // 过滤器, 找到满足条件的元素
            let list = p.emoticonsList.filter({ (emoticon) -> Bool in
                return emoticon.chs == str
            })
            if let l = list.last {
                return l
            }
        }
        
        return nil
    }
    
    override init() {
        super.init()
        
        loadEmoticons()
    }
    
    private func loadEmoticons() {
        
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")
        let dict = NSDictionary(contentsOfFile: path!)
        if let packages = dict!["packages"] as? [[String: AnyObject]] {
            for item in packages {
                let Id = item["id"] as! String
                
                loadModel(Id)
//                print(emoticonPackages.last?.emoticonsList.count)
            }
        }
    }
    
    
    private func loadModel(id: String) {
        let path = NSBundle.mainBundle().pathForResource("Info.plist", ofType: nil, inDirectory: "Emoticons.bundle/\(id)")
        let dict = NSDictionary(contentsOfFile: path!)
        if let groupName = dict?["group_name_cn"], let emoticons = dict?["emoticons"] {
            // 注意: 不要直接拿info.plist下的id, 这个id和表情包名不同
            let emoticons = EmoticonPackages(id: id, group_name_cn: groupName as? String, emoticons: emoticons as? [[String : String]])
            emoticonPackages.append(emoticons)
        }
        
    }
    
}
